<template>
  <!-- 支付确认页面 -->
  <view class="main">
    <!-- 商品展示 -->
    <view class="goods">
      <view class="card">
        <image class="datu" :src="goodsData.goodsImg" mode="aspectFill"></image>
        <view class="mengceng"></view>
        <view class="text">
          <view class="title">{{ goodsData.goodsName }}</view>
          <view class="message">{{ goodsData.goodsBrief }}</view>
          <view class="price">
            <view class="jiage">
              <s>{{ goodsData.price ? "￥" + goodsData.price : "" }}</s>
              <text>￥{{ goodsData.presentPrice }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 无收货地址 -->
    <navigator
      url="/pages/webGoods/receiverAddress?type=1"
      hover-class="none"
      class="adress"
      v-if="!is_adress"
    >
      <text>请选择收货地址：</text>
      <image src="../../imges/you.png" mode="aspectFill"></image>
    </navigator>
    <!-- 地址显示 -->
    <navigator
      url="/pages/webGoods/receiverAddress?type=1"
      hover-class="none"
      class="noAdress"
      v-if="is_adress"
    >
      <view class="left">
        <view class="top">
          <text class="name">{{ name }}</text>
          <text class="phone">{{ phone }}</text>
        </view>
        <view class="dizhi">{{ address }}</view>
      </view>
      <image src="../../imges/you.png" mode="aspectFill"></image>
    </navigator>
    <!-- 运费 -->
    <view class="freight">
      <text>运费：</text>
      <text class="right">商家包邮</text>
    </view>
    <!-- 购买数量 -->
    <view class="buyNum">
      <text>购买数量：</text>
      <view class="num">
        <view :class="[num > 1 ? 'left' : 'activeL']" @tap="subtract">-</view>
        <view class="center">
          <input
            type="number"
            @input="watchinput"
            :value="num"
            v-model="num_"
            min="1"
            max="99"
            maxlength="2"
          />
        </view>
        <view :class="[num >= 99 ? 'right' : 'activeR']" @tap="add">+</view>
      </view>
    </view>
    <!-- 总价 -->
    <view class="totalPrice">
      <text>总价：</text>
      <text class="price"
        >￥{{ (goodsData.presentPrice * num).toFixed(2) }}</text
      >
    </view>
    <view class="pay" @tap="weixinZhifu"> 微信支付 </view>
    <view class="lhzheZhao" @tap="queRen" v-if="is_Block">
      <view class="modal">
        <view class="header">提示</view>
        <view class="text">该商品已下架</view>
        <view class="btn_">
          <view class="left" @tap.stop="queRen">确认</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from "../../utils/request.js";
var jweixin = require("jweixin-module");
export default {
  data() {
    return {
      is_adress: false,
      is_Block: false,
      num: 1,
      goodsId: "",
      tieziId: "",
      addressId: "",
      name: "",
      phone: "",
      address: "",
      goodsData: {},
      payData: {},
      num_: 1,
    };
  },
  watch: {
    num(new1, old1) {
      if (new1 < 1) {
        this.num = 1;
      } else if (new1 <= 99) {
        this.num = new1;
      } else if (new1 > 99) {
        this.num = 99;
      }
    },
  },
  // watch:{
  //       num:{
  //         handler:(val,oldVal)=>{
  //           val = Number(val);
  //           if(val != val){
  //             this.num = oldVal;
  //           }else if(val > 99){
  //             this.num = oldVal;
  //           }else{
  //             this.num = val;
  //           }
  //         },
  //         deep:true
  //     }
  // },
  onShow() {
    const that = this;
    uni.getStorage({
      key: "address",
      success: function (res) {
        that.address = res.data.provinceCity + " " + res.data.fullAddress;
        that.name = res.data.receiveName;
        that.phone = res.data.receivePhone;
        that.addressId = res.data.id;
        that.is_adress = true;
        console.log(res.data);
      },
    });
    uni.removeStorage({
      key: "address",
      success: function (res) {
        console.log("success");
      },
    });
  },
  onLoad(option) {
    this.goodsId = option.id;
    this.tieziId = option.tieziId;
    this.goodsList(option.id);
    this.defaultAddress();
  },
  updata() {
    if (this.num >= 99) {
      this.num = 99;
      this.num_ = 99;
    }
  },
  methods: {
    watchinput(e) {
      setTimeout(() => {
        if (e.detail.value === 0) {
          this.num = 1;
          // this.num_ = 1
        } else {
          this.num = Number(e.detail.value);
          this.num_ = Number(e.detail.value);
        }
      }, 20);
    },
    queRen() {
      uni.navigateBack({
        delta: 1,
      });
    },
    goodsList(id) {
      let token = uni.getStorageSync("token");
      const that = this;
      if (!token) {
        uni.showToast({
          title: "请授权登录再操作！",
          duration: 2000,
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateTo({
            url: "/pages/index/index",
          });
        }, 2000);
      } else {
        request({
          url: "app/goodsOrder/goodsDetail",
          method: "POST",
          header: {
            "content-type": "application/json;charset=UTF-8",
            "api-client": "72e0fee8172411ea995200163e05ff66",
            "api-version": "1.3.3",
            "Source-Type": 7,
            token: token,
          },
          data: {
            id: id,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            that.goodsData = res.data.data;
          } else if (res.data.code == 500) {
            this.is_Block = true;
          } else if (res.data.code == 401) {
            uni.showToast({
              title: "登录失效，请重新授权登录！",
              duration: 2000,
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "/pages/index/index",
              });
            }, 2000);
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: "none",
            });
          }
        });
      }
    },
    // 获取默认地址
    defaultAddress() {
      let token = uni.getStorageSync("token");
      const that = this;
      if (!token) {
        uni.showToast({
          title: "请授权登录再操作！",
          duration: 2000,
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateTo({
            url: "/pages/index/index",
          });
        }, 2000);
      } else {
        request({
          url: "app/goods/getDefaultOrderAddress",
          method: "POST",
          header: {
            "content-type": "application/json;charset=UTF-8",
            "api-client": "72e0fee8172411ea995200163e05ff66",
            "api-version": "1.3.3",
            "Source-Type": 7,
            token: token,
          },
          data: {},
        }).then((res) => {
          if (res.data.code == 200) {
            if (res.data.data) {
              that.is_adress = true;
              that.address =
                res.data.data.provinceCity + " " + res.data.data.fullAddress;
              that.addressId = res.data.data.id;
              that.name = res.data.data.receiveName;
              that.phone = res.data.data.receivePhone;
            }
          } else if (res.data.code == 401) {
            uni.showToast({
              title: "登录失效，请重新授权登录！",
              duration: 2000,
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "/pages/index/index",
              });
            }, 2000);
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: "none",
            });
          }
        });
      }
    },
    subtract() {
      if (this.num == 1) {
        this.num = 1;
        this.num_ = 1;
      } else {
        this.num--;
        this.num_--;
      }
    },
    add() {
      if (this.num >= 99) {
        this.num = 99;
        this.num_ = 99;
      } else {
        this.num++;
        this.num_++;
      }
    },
    //获取支付参数
    weixinZhifu() {
      if (this.num >= 99) {
        this.num = 99;
      }
      if (this.num <= 0) {
        this.num = 1;
        uni.showToast({
          title: "商品数量至少为1",
          duration: 500,
          icon: "none",
        });
      }
      if (this.num_ == 0) {
        this.num_ = 1;
      }
      // console.log(this.num)
      let token = uni.getStorageSync("token");
      const that = this;
      if (this.address == "" || this.addressId == "") {
        uni.showToast({
          title: "请选择收货地址",
          duration: 2000,
          icon: "none",
        });
      } else {
        if (!token) {
          uni.showToast({
            title: "请授权登录再操作！",
            duration: 2000,
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/index/index",
            });
          }, 2000);
        } else {
          request({
            url: "app/goodsOrder/pay",
            method: "POST",
            header: {
              "content-type": "application/json;charset=UTF-8",
              "api-client": "72e0fee8172411ea995200163e05ff66",
              "api-version": "1.3.3",
              "Source-Type": 7,
              token: token,
            },
            data: {
              nums: that.num,
              totalPrice: (that.goodsData.presentPrice * that.num).toFixed(2),
              addressId: that.addressId,
              prepaymentRecordId: "",
              payWay: 4,
              goodsInfoId: that.goodsId,
            },
          }).then((res) => {
            if (res.data.code == 200) {
              that.payData = res.data.data.prepayDate;
              that.payRequest(res.data.data.prepayDate);
              console.log(that.payData, "-----------that.payData");
            } else if (res.data.code == 401) {
              uni.showToast({
                title: "登录失效，请重新授权登录！",
                duration: 2000,
                icon: "none",
              });
              setTimeout(() => {
                uni.navigateTo({
                  url: "/pages/index/index",
                });
              }, 2000);
            } else {
              uni.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: "none",
              });
            }
          });
        }
      }
    },
    // 调起支付
    payRequest(payData) {
      let that = this;
      request({
        //获取appid
        url: "wechat/portal/jsapiSignature/",
        method: "POST",
        header: {
          "Content-Type": "application/json",
          "api-client": "72e0fee8172411ea995200163e05ff66",
          "api-version": "1.3.3",
          "Source-Type": 7,
          // 'Referer' : 'https://test.yiqilaiwang.com'
        },
        data: {
          url: window.location.href.split("#")[0], //后台通过域名进行授权
        },
      }).then((res) => {
        if (res.statusCode == 200) {
          //获取成功
          jweixin.config({
            debug: false, // 开启调试模式，发布的时候改为false
            appId: res.data.appId, // 必填，公众号的唯一标识
            timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            signature: res.data.signature, // 必填，签名
            jsApiList: ["chooseWXPay"], // 必填，需要使用的JS接口列表
          });
          jweixin.ready(function () {
            jweixin.checkJsApi({
              jsApiList: ["chooseWXPay"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
              success: function (res) {
                console.log("成功");
                console.log(res);
              },
              fail: function (res) {
                console.log("res");
                console.log(res);
              },
            });
            jweixin.chooseWXPay({
              appId: payData.appId,
              timestamp: payData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: payData.nonceStr, // 支付签名随机串，不长于 32 位
              package: `prepay_id=${payData.prepay_id}`, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
              signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: payData.paySign, // 支付签名
              success: function (res) {
                // 支付成功后的回调函数
                uni.showToast({
                  icon: "none",
                  title: "支付成功",
                  duration: 2000,
                });
                // setTimeout(function () {
                //   uni.navigateBack({
                //     delta: 1,
                //   });
                // }, 1500);
                uni.redirectTo({
                  url:
                    "/pages/index/trickDetail?id=" + that.tieziId + "&type=1",
                });
                console.log("paysuccess");
                console.log(res);
                var route = "payResult" + "?type=1";
                uni.navigateTo({
                  url: route,
                });
              },
              cancel: function (r) {
                var route = "payResult" + "?type=2";
                uni.navigateTo({
                  url: route,
                });
              },
              fail: function (res) {
                console.log("payfail");
                console.log(res);
                var route = "payResult" + "?type=0";
                uni.navigateTo({
                  url: route,
                });
              },
            });
          });

          jweixin.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            /*alert("config信息验证失败");*/
          });
        } else if (res.data.code == 401) {
          uni.showToast({
            title: "登录失效，请重新授权登录！",
            duration: 2000,
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/index/index",
            });
          }, 2000);
        } else {
          uni.showToast({
            title: res.data.msg,
            duration: 1500,
            icon: "none",
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  padding: 0 32rpx;
}

.lhzheZhao {
  position: fixed;
  z-index: 9999;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;

  .modal {
    position: relative;
    background-color: #fff;
    border-radius: 8rpx;
    width: 520rpx;
    height: 300rpx;
    box-sizing: border-box;
    padding: 0 40rpx;
    padding-top: 30rpx;

    .header {
      width: 100%;
      text-align: center;
      font-size: 40rpx;
      font-family: PingFang SC;
      font-weight: 500;
    }

    .text {
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(49, 49, 49, 1);
      width: 100%;
      text-align: center;
      margin-top: 30rpx;
    }

    .btn_ {
      // position: absolute;
      // bottom: 0;
      height: 85rpx;
      border-top: 2rpx solid #eee;
      width: 100%;
      display: flex;
      margin-top: 60rpx;

      .left {
        width: 100%;
        height: 85rpx;
        line-height: 85rpx;
        text-align: center;
        font-size: 32rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #0476fc;
      }
    }
  }
}

.goods {
  display: flex;
  flex-wrap: wrap;

  .card {
    width: 686rpx;
    height: 380rpx;
    position: relative;

    .datu {
      width: 686rpx;
      height: 380rpx;
      border-radius: 8rpx;
    }

    .mengceng {
      width: 100%;
      height: 225rpx;
      position: absolute;
      bottom: 0;
      left: 0;
      background: linear-gradient(
        180deg,
        rgba(0, 0, 0, 0) 0%,
        rgba(0, 0, 0, 0.92) 100%
      );
      box-shadow: 0px 2px 20px 0px rgba(255, 255, 255, 0.1);
      opacity: 0.72;
    }

    .text {
      width: 100%;
      height: 170rpx;
      position: absolute;
      bottom: 0;
      left: 0;
      color: #ffffff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 0 23rpx;
      padding-bottom: 60rpx;

      box-sizing: border-box;

      .title {
        font-size: 34rpx;
        font-weight: bold;
      }

      .message {
        display: flex;
        align-items: center;
        margin-top: 15rpx;
        box-sizing: border-box;
        font-size: 24rpx;
        color: #fb8724;
        margin-bottom: 20rpx;
      }

      .price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;

        .jiage {
          s {
            font-size: 30rpx;
            color: #999999;
            margin-right: 20rpx;
          }

          text {
            font-size: 34rpx;
            color: #ffd510;
          }
        }
      }
    }

    .join {
      width: 148rpx;
      height: 52rpx;
      line-height: 52rpx;
      text-align: center;
      position: absolute;
      top: 32rpx;
      right: 24rpx;
      font-family: PingFang-SC-Medium;
      font-size: 26rpx;
      color: #ffffff;
      background: linear-gradient(90deg, #399aff 0%, #1571eb 100%);
      box-shadow: 0px 0px 17px 4px rgba(0, 0, 0, 0.06);
      border-radius: 26px;
    }
  }
}

.adress,
.freight,
.buyNum,
.totalPrice {
  width: 100%;
  height: 45rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eeeeee;

  text {
    font-size: 32rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #888888;
  }
}

.adress {
  image {
    width: 26rpx;
    height: 32rpx;
  }
}

.noAdress {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eeeeee;
  font-size: 32rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333333;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .top {
    .phone {
      margin-left: 15rpx;
      color: #888888;
    }
  }

  .dizhi {
    font-size: 30rpx;
  }

  image {
    width: 26rpx;
    height: 32rpx;
  }
}

.freight {
  .right {
    color: #333333;
  }
}

.buyNum {
  .num {
    width: 200rpx;
    height: 60rpx;
    display: flex;
    border: 1rpx solid #979797;
    border-radius: 10rpx;
    color: #333333;

    .left {
      width: 50rpx;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      color: #333333;
    }

    .activeL {
      width: 50rpx;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      color: #cccccc;
    }

    .activeR {
      width: 50rpx;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      color: #333333;
    }

    .center {
      width: 100rpx;
      height: 60rpx;
      border-left: 1rpx solid #979797;
      border-right: 1rpx solid #979797;
      text-align: center;
      line-height: 60rpx;
      font-size: 32rpx;

      input {
        height: 60rpx;
      }
    }

    .right {
      width: 50rpx;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      color: #cccccc;
    }
  }
}

.totalPrice {
  .price {
    font-weight: 500;
    color: #ff6400;
  }
}

.pay {
  width: 440rpx;
  height: 88rpx;
  background: #22b555;
  border-radius: 44rpx;
  font-size: 34rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  line-height: 88rpx;
  margin: 0 auto;
  margin-top: 109rpx;
}
</style>
